package com.share.thread;

/**
 * @desc: 打印 ABC 5次 3个线程
 * @author:caifan
 * @date:2022/1/20
 */
public class TakeTurn03 {
    public static void main(String[] args) {
        Print03 print03 = new Print03();
        new Thread(() -> print03.printA()).start();
        new Thread(() -> print03.printB()).start();
        new Thread(() -> print03.printC()).start();
    }
}

class Print03 {
    private volatile int flag = 0;

    public synchronized void printA() {
        for (int i = 0; i < 5; i++) {
            while (flag != 0) {
                try {
                    wait();
                } catch (Exception e) {

                }
            }
            System.out.print("A");
            flag = 1;
            notifyAll();
        }
    }
    public synchronized void printB() {
        for (int i = 0; i < 5; i++) {
            while (flag != 1) {
                try {
                    wait();
                } catch (Exception e) {

                }
            }
            System.out.print("B");
            flag = 2;
            notifyAll();
        }
    }

    public synchronized void printC() {
        for (int i = 0; i < 5; i++) {
            while (flag != 2) {
                try {
                    wait();
                } catch (Exception e) {

                }
            }
            System.out.print("C");
            flag = 0;
            notifyAll();
        }
    }
}
